/**
 * Created by Administrator on 2015/4/21.
 */
(function(BaseClass,$,xhr){

	var deepCopy = function(destination, source){
		for (var property in source) {
			if (typeof source[property] === "object" && source[property] !== null && destination[property]) {
				deepCopy(destination[property], source[property]);
			} else {
				destination[property] = source[property];
			}
		}
		return destination;
	};

	//软终端验证核心逻辑 pc&mobile两端通用
	var TerminalClass = BaseClass.extend({
		PAYTYPE : {
			"0" : "账户余额支付",
			"1" : "支付宝支付",
			"2" : "授信支付",
			"3" : "产品自销",
			"4" : "现场支付",
			"5" : "微信支付"
		},
		PAYSTATUS : {
			0 : "景区到付",
			1 : "已成功",
			2 : "未支付"
		},
		ORDERSTATUS : {
			"0" : "未使用",
			"1" : "已使用",
			"2" : "已过期",
			"3" : "已取消",
			"4" : "凭证码被替代",
			"5" : "被终端撤销(已取消)",
			"6" : "被终端撤销(已使用)"
		},
		api : {
			//获取产品
			fetchProduct : "terminal_chk.html",
			//验证&搜索订单
			terminal : "http://www.12301.cc/module/wxh/terminal/call/terminal.php"
		},
		checkIsAdmin : function(){ return false},
		init : function(){

		},
		/**
		 * 获取远程产品(搜索)
		 * @param keyword  关键字   为空时默认获取全部产品
		 */
		fetchProduct : function(keyword,callbacks,sid){
			var that = this;
			var keyword = keyword || "";
			var api = this.api.fetchProduct;
			var callbacks = callbacks || {};
			var fn = new Function;
			var sid = sid || "";
			var loading = callbacks.loading || fn;
			var removeloading = callbacks.removeloading || fn;
			var timeout = callbacks.timeout || fn;
			var serverError = callbacks.serverError || fn;
			var empty = callbacks.empty || fn;
			var success = callbacks.success || fn;
			var xhr;
			xhr = this.ajax({
				url : api,
				type : "GET",
				dataType : "json",
				ttimeout : 15 * 1000,
				data : {
					"action" : "queryproduct",
					"keyword" : keyword,
					"sid" : sid
				},
				loading : function(){
					that.fire("onProductLoading");
					loading();
				},
				removeLoading : function(){
					that.fire("onProductRemoveLoading");
					removeloading();
				},
				timeout : function(res) {
					that.fire("onProductTimeout",res);
					timeout(res);
				},
				serverError : function(res) {
					that.fire("onProductServerError",res);
					serverError(res);
				}
			},function(res){
				if(res.status=="success"){
					if(res.list && res.list.length>0){
						that.fire("onProductSuccsee",res);
						success(res);
						console.log(res.list.length)
					}else{
						that.fire("onProductEmpty",res);
						empty(res);
					}
				}else{
					that.fire("onProductServerError",res);
					serverError(res);
				}
			})
			return xhr;
		},
        /**
         * 手机多单验证
         * @param salerid  产品编号
         * @param number   证码，电话号码，身份证  三者任意一种
         */
        CkeckNumber:function(target,code)
        {
            var that = this;
            var api = this.api.terminal;
            this.ajax({
                url : api,
                type : "GET",
                dataType : "json",
                data : {
                    id      : $("#term_prodId").text(),
                    terminal: $("#term_termNum").text(),
                    salerid : $("#term_prodNum").text(),
                    code    : code
                },
                loading : function(){ that.onQueryOrderLoading()},
                removeLoading : function(){ that.onQueryOrderRemoveLoading()},
                timeout : function(){ that.onQueryOrderTimeout()},
                serverError : function(){that.onQueryOrderServerError()}
            },function(res){
                if(res.state=="success" && res.multi=="1" ) {
                    that.onQueryOrderCheck(res);
                }else if(Object.prototype.toString.call(res) == "[object Object]" && res.status=="fail" && res.code==0) {
                    that.onQueryOrderLoginOut(res);
                }else if(Object.prototype.toString.call(res) == "[object Object]" && res.status=="fail") { //空数据
                    that.onQueryOrderEmpty(res);
                }else{
                    var data = res;
                    for(var i in data){
                        var d = data[i];
                        var flag = [];
                        var payTypeTip = "";
                        var checkBtnTxt = "验 证";
                        var checkBtnCls = "";
                        var orderStatus = d["status"];  //订单状态 标识是否已验证
                        var payType = d["pmode"];       //支付方式
                        var payStatus = d["paystatus"]; //支付状态
                        var ticketTxt = "未验证";
                        var readonly = "";
                        var ptype = d["ptype"] || "";
                        ptype = ptype.toUpperCase();

                        //"1" : "已使用",
                        //"2" : "已过期",
                        //"3" : "已取消",
                        if(orderStatus==1 || orderStatus==3 || (orderStatus==2 && !isAdmin)){
                            flag.push(ORDERSTATUS[orderStatus]);
                            checkBtnCls = "disabled";
                            checkBtnTxt = ORDERSTATUS[orderStatus] + "订单无法验证";
                            ticketTxt = ORDERSTATUS[orderStatus];
                        }
                        if(orderStatus==2 && isAdmin){
                            flag.push(ORDERSTATUS[orderStatus]);
                            ticketTxt = ORDERSTATUS[orderStatus];
                        }
                        if(payType==4){ //现场支付
                            flag.push(PAYTYPE[payType]);
                            payTypeTip = '<p class="payTypeTip">请先确认游客已现场付费，然后给予验证</p>';
                        }
                        if(payStatus==2){
                            flag.push("未支付");
                            checkBtnTxt = "未支付订单无法支付";
                            checkBtnCls = "disabled";
                        }
                        if(ptype=="F" || ptype=="C") readonly = "readonly";
                        d["flag"] = flag;
                        d["payTypeTip"] = payTypeTip;
                        d["checkBtnTxt"] = checkBtnTxt;
                        d["checkBtnCls"] = checkBtnCls;
                        d["ticketTxt"] = ticketTxt;
                        d["readonly"] = readonly;
                    }
                    that.onQueryOrderSuccess(data);
                }
            })
        },
		/**
		 * 查询某个产品下的订单
		 * @param salerid  产品编号
		 * @param number   证码，电话号码，身份证  三者任意一种
		 */
		queryOrder : function(salerid,number){
			if(!salerid || !number){
				cconsole && console.log("缺省salerid景区6位帐号 或 voucher凭证码/手机号/身份证");
				return false;
			}
			number = $.trim(number);
			var that = this;
			var api = this.api.terminal;
			var ORDERSTATUS = this.ORDERSTATUS;
			var PAYTYPE = this.PAYTYPE;
			var isAdmin = this.checkIsAdmin();
			this.ajax({
				url : api,
				type : "GET",
				dataType : "json",
				data : {
                    id      : salerid,
                    voucher : number,
                    terminal: $("#term_termNum").text(),
                    salerid : $("#term_prodNum").text(),
                    data    : "1"
				},
				loading : function(){ that.onQueryOrderLoading()},
				removeLoading : function(){ that.onQueryOrderRemoveLoading()},
				timeout : function(){ that.onQueryOrderTimeout()},
				serverError : function(){that.onQueryOrderServerError()}
			},function(res){
                if(res.state=="success" && res.multi=="1" ) {
                    that.onQueryOrderCheck(res);
                }else if(Object.prototype.toString.call(res) == "[object Object]" && res.status=="fail" && res.code==0) {
                    that.onQueryOrderLoginOut(res);
                }else if(Object.prototype.toString.call(res) == "[object Object]" && res.status=="fail"){ //空数据
                    that.onQueryOrderEmpty(res);
                   
                }
                else {
                    
					var data = res;
					for(var i in data){
						var d = data[i];
						var flag = [];
						var payTypeTip = "";
						var checkBtnTxt = "验 证";
						var checkBtnCls = "";
						var orderStatus = d["status"];  //订单状态 标识是否已验证
						var payType = d["pmode"];       //支付方式
						var payStatus = d["paystatus"]; //支付状态
						var ticketTxt = "未验证";
						var readonly = "";
						var ptype = d["ptype"] || "";
						ptype = ptype.toUpperCase();

						//"1" : "已使用",
						//"2" : "已过期",
						//"3" : "已取消",
						if(orderStatus==1 || orderStatus==3 || (orderStatus==2 && !isAdmin)){
							flag.push(ORDERSTATUS[orderStatus]);
							checkBtnCls = "disabled";
							checkBtnTxt = ORDERSTATUS[orderStatus] + "订单无法验证";
							ticketTxt = ORDERSTATUS[orderStatus];
						}
						if(orderStatus==2 && isAdmin){
							flag.push(ORDERSTATUS[orderStatus]);
							ticketTxt = ORDERSTATUS[orderStatus];
						}
						if(payType==4){ //现场支付
							flag.push(PAYTYPE[payType]);
							payTypeTip = '<p class="payTypeTip">请先确认游客已现场付费，然后给予验证</p>';
						}
						if(payStatus==2){
							flag.push("未支付");
							checkBtnTxt = "未支付订单无法支付";
							checkBtnCls = "disabled";
						}
						if(ptype=="F" || ptype=="C") readonly = "readonly";
						d["flag"] = flag;
						d["payTypeTip"] = payTypeTip;
						d["checkBtnTxt"] = checkBtnTxt;
						d["checkBtnCls"] = checkBtnCls;
						d["ticketTxt"] = ticketTxt;
						d["readonly"] = readonly;
					}
                    that.onQueryOrderSuccess(data);
				}
			})
		},
		/**
		 * 验票
		 * @param btn  点击哪个按钮验票
		 * @param data 验票所需发送的所有数据 json字符串
		 */
		terminalCheck : function(btn,data){
			var that = this;
			var api = this.api.terminal;
			this.ajax({
				url : api,
				type : "POST",
				dataType : "json",
				data : {
					data : data
				},
				loading : function(){ that.onCheckLoading(btn,data)},
				removeLoading : function(){ that.onCheckRemoveLoading(btn,data)},
				timeout : function(res){ that.onCheckTimeout(btn,data,res)},
				serverError : function(res){ that.onCheckServerError(btn,data,res)}
			},function(res){
				if(res && res.status && res.status=="success"){
					that.onCheckSuccess(btn,data,res);
				}else if(res.status=="fail" && res.code && res.code==0){ //登录过期
					that.onCheckLoginOut(res);
				}else{
					that.onCheckFail(btn,data,res);
				}
			})
		},
		ajax : function(config,callback){
			var ajax = null;
			var fn = PFT_GLOBAL.EMPTY_FN;
			config = config || {};
			var url = config.url;
			if(!url){
				console && console.log("involed url");
				return false;
			}
			var type = config.type || "GET";
			var dataType = config.dataType || "json";
			var data = config.data || {};
			var ttimeout = config.ttimeout || PFT_GLOBAL.CONFIG.AJAX_TIMEOUT;
			var loading = config.loading || fn;
			var removeLoading = config.removeLoading || fn;
			var timeout = config.timeout || fn;
			var serverError = config.serverError || fn;
			var callback = typeof callback == "function" ? callback : fn;
			ajax = xhr({
				url : url,
				type : type,
				dataType : dataType,
				timeout : ttimeout,
				data : data,
				beforeSend : function(){ loading()},
				success : function(res){
					removeLoading();
					callback(res);
				},
				error : function(xhr,txt){
					removeLoading();
					if(txt == "timeout"){
						timeout();
					}else{
						serverError();
					}
				}
			})
			return ajax;
		},

		//给子类覆盖
		onCheckLoading : function(btn,data){},
		onCheckRemoveLoading : function(btn,data){},
		onCheckTimeout : function(btn,data,res){},
		onCheckServerError : function(btn,data,res){},
		onCheckFail : function(btn,data,res){},
		onCheckSuccess : function(btn,data,res){},
		onCheckLoginOut : function(res){},
		onQueryOrderLoading : function(){},
		onQueryOrderRemoveLoading : function(){},
		onQueryOrderTimeout : function(res){},
		onQueryOrderServerError : function(res){},
		onQueryOrderSuccess : function(res){},
		onQueryOrderEmpty : function(res){},
		onQueryOrderLoginOut : function(){},
        onQueryOrderCheck : function(){}
	});

	window.TerminalClass = TerminalClass;

})(BaseClass,$,$.ajax);